package middleware

import (
	"context"
	"net/http"

	"strings"

	"github.com/zeromicro/go-zero/rest/httpx"
)

type AuthMiddleware struct {
}

func NewAuthMiddleware() *AuthMiddleware {
	return &AuthMiddleware{}
}

func (m *AuthMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// 跳过登录接口
		if r.URL.Path == "/api/login" {
			next(w, r)
			return
		}

		// 从Header获取Token
		authHeader := r.Header.Get("Authorization")
		if authHeader == "" {
			httpx.Error(w, httpError("未提供认证令牌", http.StatusUnauthorized))
			return
		}

		// 提取Bearer Token
		parts := strings.Split(authHeader, " ")
		if len(parts) != 2 || parts[0] != "Bearer" {
			httpx.Error(w, httpError("认证令牌格式错误", http.StatusUnauthorized))
			return
		}

		token := parts[1]

		//// 验证Token并获取用户信息
		//userID, username, err := m.svcCtx.Auth.VerifyToken(token)
		//if err != nil {
		//	httpx.Error(w, httpError("认证令牌无效", http.StatusUnauthorized))
		//	return
		//}

		// 将用户信息存入上下文
		ctx := context.WithValue(r.Context(), "userID", "userID")
		ctx = context.WithValue(ctx, "username", "username")
		ctx = context.WithValue(ctx, "token", token)

		next(w, r.WithContext(ctx))
	}
}

func httpError(msg string, code int) error {
	return &HttpError{
		Message: msg,
		Code:    code,
	}
}

type HttpError struct {
	Message string `json:"message"`
	Code    int    `json:"code"`
}

func (e *HttpError) Error() string {
	return e.Message
}
